<template>
  <view class="page custom-page">
    <custom-head gradient back title="添加老师">
      <view class="tool" slot="right">
      </view>
    </custom-head>

    <view class="addition">
      <view class="touxiang-box flex col a-center j-c-c">
        <u-upload 
          max-count="1"
          :file-list="fileList"
          :form-data="{ type: 'avatar' }"
          :header="{ Authorization: token }"
          :action="BASE_URL + '/file/upload'"
          @on-change="onSuccess"
          @on-remove="omRemove"
        >
          <view class="touxiang" slot="addBtn">
            <image :src="form.avatar" mode="widthFix"></image>
          </view>
        </u-upload>
        <text>头像</text>
      </view>

      <view class="form">
        <u-form :model="form" ref="uForm" label-width="180">
          <u-form-item label="姓名">
            <u-input v-model="form.name" placeholder="请输入学生姓名（昵称)16个字符内" />
          </u-form-item>
          <u-form-item label="性别">
            <u-radio-group v-model="form.sex">
              <u-radio v-for="(item, index) in sexList" :key="index" :name="item.name">{{ item.name }}</u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item label="老师状态">
            <u-radio-group v-model="form.status">
              <u-radio v-for="(item, index) in stateList" :key="index" :name="item.name">{{ item.name }}</u-radio>
            </u-radio-group>
          </u-form-item>

          <u-form-item label="所在班级">
            <u-input v-model="form.className" placeholder="请选择班级" @click="showPopup = true" />
            <!-- <u-select v-model="showClass" mode="single-column" :list="classList" @confirm="selectClass" :default-value="classDefaultValueList"></u-select> -->
            <u-icon name="arrow-down" color="#91959B" size="26"></u-icon>
          </u-form-item>

          <u-form-item label="联系电话">
            <u-input v-model="form.phone" placeholder="请输入老师的联系电话" />
          </u-form-item>

          <u-form-item label="用户角色">
            <u-input v-model="form.user" placeholder="请选择角色"  @click="showUser = true" />
            <u-select v-model="showUser" mode="single-column" :list="userList" @confirm="selectUser" :default-value="userDefaultValueList"></u-select>
            <u-icon name="arrow-down" color="#91959B" size="26"></u-icon>
          </u-form-item>
        </u-form>
        <view class="button submit" @click="handleSubmit">保存</view>
      </view>
    </view>
    <!-- <u-action-sheet cancelText="取消" :list="list" v-model="show" @click="enterPage"></u-action-sheet> -->

    <u-popup v-model="showPopup" mode="bottom" :mask-close-able="false">
      <view class="popup_content">
        <view class="popup_top">
          <view @click="cancelPopup">取消</view>
          <view class="blue" @click="confirmPopup">确认</view>
        </view>

          <scroll-view class="content_item" scroll-y="true">
            <view class="item" v-for="(item, index) in classList" @click="handleItem(index)">
              <view>{{ item.label }}</view>
              <u-checkbox v-model="item.check"></u-checkbox>
            </view>
          </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { addTeacher, getTeacherDetail, updateTeacher } from '../../api/modules/teacher';
// import { getClassTeachers } from '../../api/modules/class';
import { getSchoolRole } from '../../api/modules/school';
import { BASE_URL } from '../../api/config'
import { init } from '../../utils/getData';

  export default {
    data () {
      return {
        sexList: [{
          name: '男'
        }, {
          name: '女'
        }, {
          name: '保密'
        }],
        sexMap: {
          '男': 1,
          '女': 2,
          '保密': 0,
        },
        sexLists: ['保密', '男', '女'],
        stateList: [{
          name: '在职'
        }, {
          name: '离职'
        }, {
          name: '停职'
        }],
        statusMap: {
          '在职': 1,
          '离职': -1,
          '停职': 0,
        },
        statusMaps: {
          0 : '停职',
          1 : '在职',
          '-1' : '离职'
        },
        form: {
          sex: '保密',
          status: '任职中',
          phone: '',
          className: '', // 班级
          name: '', 
          user: '', // 角色
          avatar: '../../static/img/avatar.png', 
        },
        rules: {},
        // show: false,
        // list: [{
        //   text: '批量添加老师信息',
        //   path: '/pages/school/batchAddition'
        // }],

        showClass: false,
				classList: [], // 班级数据列表
        classDefaultValueList: [0], // 班级默认选中第一项

        showUser: false,
				userList: [], // 角色数据列表
        userDefaultValueList: [0], // 班级默认选中第一项

        static_uri: getApp().globalData.glb_list.config.static_uri, // 获取全局配置文件
        BASE_URL,
        token: uni.getStorageSync('token'),
        fileList: [], // img
        showPopup: false, // popup 弹出框显示
        classCid: '', // 班级选中的 cid
      }
    },
    onReady () {
      this.$refs.uForm.setRules(this.rules);
    },
    mounted() {
      // console.log('glbId', this.glbId)
      this.classList = getApp().globalData.glb_list.classList.filter(i => i.sid === this.glbId).map(item => ({label: item.name, value: item.id, check: false}))

      this.userList = getApp().globalData.glb_list.rolesList.map(item => ({label: item.name, value: item.id}))

      if (this.$route.query?.id) {
        this._getTeacherDetail(this.$route.query?.id)
      }
    },

    methods: {
      cancelPopup() { // 取消弹出框
        this.showPopup = false; 
        this.classCid = '';
        this.form.className = '';
        this.classList = this.classList.map((item, i) => ({...item, check: false}))
        console.log('--quxiao', this.classList)
      },
      confirmPopup() { // 确定弹出框
        this.showPopup = false
        let idStr = this.classList.filter(i => i.check).map(i => i.value).join(',');
        this.classCid = idStr;
        console.log('确定选中 cid', idStr)
        this.form.className = this.classList.filter(i => i.check).map(i => i.label).join(',');
      },
      handleItem(index) { // 选中那一项打钩
        this.classList.map((item, i) => ({...item, check: index ===i ? !item.check : item.check }))
      },
      omRemove(index) { // 移除照片
        if (index === 0) {
          this.fileList = []
          this.form.avatar = ''
        }
      },
      onSuccess(data) {
        const res = JSON.parse(data.data)
        if (res.code == 201) {
          this.form.avatar = res.data.path
        } else {
          this.$refs.uUpload.clear()
          this.$u.toast('上传失败')
        }
      },
      handleSubmit() {
        const { phone, name, sex, status, user, className, avatar  } = this.form || {};
        let userIndex = this.userDefaultValueList[0];
        let classIndex = this.classDefaultValueList[0];
        let avatar_path = ''; // 对保存的path做切割
        if (avatar.indexOf('com') > 0) {
          avatar_path = avatar.split('com')[1]
        }

        let data = {
          phone,
          name,
          status: this.statusMap[status],
          rid: this.userList[userIndex]?.value, // 角色  // 之前是 sid的
          // cid: this.classList[classIndex]?.value, // 班级
          cid: this.classCid, // 班级
          sex: this.sexMap[sex],  // 性别
          avatar: avatar_path ? avatar_path : avatar,
          sid: this.glbId,
        }
        console.log('form', data)

        if (this.$route.query?.id) {  // 编辑页面
          this._updateTeacher(this.$route.query?.id, data)
        } else {
          this._addTeacher(data)
        }
      },
      selectClass(e){ // 选择所在班级
        this.form.className = e[0].label
        let index = ([] && this.classList).findIndex(item => item.value === e[0].value)
        this.classDefaultValueList = [index]
      },
      selectUser(e) { // 选择用户角色
        this.form.user = e[0].label;
        let index = ([] && this.userList).findIndex(item => item.value === e[0].value)
        this.userDefaultValueList = [index]
        // console.log('---selectUser', e, this.userDefaultValueList)
      }, 

      _getTeacherDetail(id) {  // 获取老师详情的地址
        getTeacherDetail(id).then((res) => {
          const {  code, data} = res || {}
          const { sex, status, name, phone, rid, avatar, classes } = data || {}

          let userIndex = ([] && this.userList).findIndex(item => item.value === rid)
          this.userDefaultValueList = [userIndex]

          if (code === 200) {
            let item = {
              sex: this.sexLists[sex],
              status: this.statusMaps[status],
              name,
              phone,
              className: classes.map(i => i.name).join(','),  //  后端没有传回
              user: this.userList[userIndex]?.label,  // 后端返回的是 null 
              avatar: `${this.static_uri}${avatar}`
            }
            this.form = item
            let arr = [];
            classes.forEach(item => {
              arr.push(item.id)
            })
            this.classList = this.classList.map(i => ({...i, check: arr.includes(i.value)}))
          }
        })
      },

      _updateTeacher(id,data) { // 修改老师信息
        updateTeacher(id, data).then((res) => {
          const { code } = res || {}
          if (code === 201) {
            this.$u.toast('修改成功')
            init();
            uni.navigateBack({
              delta: 1
            })
          }
        })
      },


      _addTeacher(id, data) { // 添加老师信息
        addTeacher(id, data).then((res) => {
          const { code } = res || {};
          if (code === 201) {
            this.$u.toast('保存成功')
            init();
            uni.navigateBack({
              delta: 1
            })
          }
        })
      },
    }

  }
</script>
<style scoped lang="scss">
.popup_content {
  height: 600rpx;
  padding: 0 30rpx 40rpx;

  .popup_top {
    position: fixed;
    display: flex;
    justify-content: space-between;
    width: 92%;
    z-index: 99;
    background: #fff;
    padding-top: 10px;
    .blue {
      color: #2c7bff;
    }
  }

  .content_item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 60%;
    height: 480rpx;
    overflow: scroll;
    padding-top: 80rpx;
    padding-left: 16%;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;
    }
  }
}
  .touxiang-box {
    padding: 40rpx 0;
    font-size: 30rpx;
  }

  .touxiang {
    width: 150rpx !important;
    height: 150rpx !important;
    margin: auto;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 25rpx;
  }

  .touxiang image {
    width: 100%;
    height: 100%;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    background-color: #fff;
    padding: 0px 45rpx;
    overflow: hidden;
    height: calc(100vh - 386rpx);
  }

  .button {
    width: 100%;
    height: 88rpx;
    border-radius: 44rpx;
    margin: 80rpx 0 40rpx 0;
    background-color: #2979FF;
    color: #fff;
    font-size: 32rpx;
    text-align: center;
    line-height: 88rpx;
  }

  /deep/ .u-form-item--left {
    align-items: self-start !important;
  }
</style>